package com.example.crm.servlet;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.Arrays;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;



import com.example.crm.mapper.UserMapper;
import com.example.crm.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

@WebServlet("/registerchk")
public class RegisterServlet extends HttpServlet{

	SqlSessionFactory sqlSessionFactory;

	// 每次执行测试前 要执行的代码
	public RegisterServlet()
	{
		// 1. 创建SqlSessionFactoryBuilder对象
		SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();

		// 2. 加载SqlMapConfig.xml配置文件
		InputStream inputStream;
		try {
			inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
		} catch (IOException e) {
			throw new RuntimeException(e);
		}

		// 3. 创建SqlSessionFactory对象
		this.sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
	}


	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	
		// 设定编码
		req.setCharacterEncoding("utf-8");
		resp.setContentType("text/html;charset=utf-8");
		
		String username = req.getParameter("username");
		String password = req.getParameter("password");
		
		// 把用户信息放入一个User对象中
		User u = new User();
		u.setUsername(username);
		u.setPassword(password);
		
		// 调用 DAO 实现注册
		SqlSession sqlSession = sqlSessionFactory.openSession();
		UserMapper dao = sqlSession.getMapper(UserMapper.class);

		int result = 0;
		 result = dao.insert(u);

		 sqlSession.commit();
		 sqlSession.close();

		// 根据注册结果显示
		if(result==1)
		{
			// 跳转
			resp.sendRedirect("login.jsp");
		}
		else
		{
			resp.sendRedirect("register.jsp");
		}
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
		doGet(req,resp);
	}
}
